package controller;

import common.BaseServlet;
import common.CartShop;
import service.AddressDAO;
import service.CartDAO;
import service.OrderDetailDAO;
import service.OrderInfoDAO;
import service.OrderLogDAO;
import service.ProductDAO;
import service.UserDAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import bean.Address;
import bean.Cart;
import bean.Goods;
import bean.User;

/**
 * Servlet implementation class OrderComfirmServlet
 */
@WebServlet("/OrderConfirm")
public class OrderConfirmServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private static AddressDAO adao = new AddressDAO();
	private static ProductDAO pdao = new ProductDAO();
	private static OrderInfoDAO oidao = new OrderInfoDAO();
	private static OrderDetailDAO oddao = new OrderDetailDAO();
	private static OrderLogDAO oldao = new OrderLogDAO();
	private static UserDAO udao = new UserDAO();
	private static CartDAO cdao = new CartDAO();
    
    /**
     * @see BaseServlet#BaseServlet()
     */
    public OrderConfirmServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	@Override
	//用户从商品详情页的立即下单和购物车的立即结算选项进入此功能，如果未登录则要先跳往登录页面，
	//登录成功后再跳转到订单确认页
	public String basefun(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("进入订单确认页面");
		String requestURI=request.getRequestURI();  
		System.out.println("requestURI:"+requestURI);
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session=request.getSession(false);
		if(request.getSession(false)==null) {
			invalidateSession(session);
			try {
				request.getRequestDispatcher("Login?requestURI="+requestURI).forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		int ifLogin=(int) session.getAttribute("ifLogin");
		if(ifLogin==0) {
			try {
				request.getRequestDispatcher("Login?requestURI="+requestURI).forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println(request.getParameter("goodsList"));
		String goodsListStr=request.getParameter("goodsList");
		request.setAttribute("goodsListStr", goodsListStr);
		
		//获取用户收货地址
		//[{userid:1,consignee:xxx,tel:15698563259,...},...]
		int userid=((User)session.getAttribute("user")).getUserid();
		List<Address> addList=adao.queryByUserid(userid);
		StringBuffer addStr=new StringBuffer();
		addStr.append("[");
		for(Iterator<Address> it=addList.iterator();it.hasNext();) {
			Address add=it.next();
			addStr.append("{\"userid\":\""+add.getUserid()+"\",");
			addStr.append("\"addressid\":\""+add.getAddressid()+"\",");
			addStr.append("\"consignee\":\""+add.getConsignee()+"\",");
			addStr.append("\"tel\":\""+add.getTel()+"\",");
			addStr.append("\"province\":\""+add.getProvince()+"\",");
			addStr.append("\"city\":\""+add.getCity()+"\",");
			addStr.append("\"district\":\""+add.getDistrict()+"\",");
			addStr.append("\"street\":\""+add.getStreet()+"\",");
			addStr.append("\"address\":\""+add.getAddress()+"\",");
			addStr.append("\"postcode\":\""+add.getPostcode()+"\",");
			addStr.append("\"isActive\":\""+add.getIfDefault()+"\",");
			addStr.append("\"ifdefault\":\""+add.getIfDefault()+"\"},");
		}
		if(addList.size()==0||addList==null) {
			addStr.append(",");
		}
		System.out.println(addStr);
		addStr.deleteCharAt(addStr.length()-1);
		addStr.append("]");
		request.setAttribute("addStr", addStr);
		return "f:jsp/OrderConfirm";
	}
	
	/*提交订单：
	 *  提交订单前需要对商品库存表中的商品库存数量进行确认，如果购买数量大于库存则提交订单失败并返回错误信息
	 *  1.在商品详情表goods_info中减去对应商品的库存数量
		2.生成订单信息，在order_info表中生成一条新纪录，包括userid/addressid/，
		支付状态pay_status默认为0待支付，配送状态post_status默认为0待发货，
		订单状态order_status默认为0待支付，以及goods_num/totle_price/pay_price/
		points_used/post_fee/create_time/update_time
		3.生成订单详情信息，在order_detail中依次添加对应订单表中的商品信息记录，
		包括orderid/goodsid/num/price/cost/subtotal/status
		4.生成订单日志信息，在order_log表中新增一条记录，包括orderid/content:生成订单/operatorid：userid/
		operator_type：0/time
		5.在用户表user_info中修改对应用户的points/exp/level
		6.在用户的购物车对象以及表中根据购买的数量减去对应商品的数量
	 */
	public void subOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("进入订单提交页面");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		HttpSession session=request.getSession(false);
		String requestURI=request.getRequestURI();  
		if(request.getSession(false)==null||session.getAttribute("user")==null) {
			invalidateSession(session);
			try {
				request.getRequestDispatcher("Login?requestURI="+requestURI).forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		/*String addressid=request.getParameter("addressid");
		System.out.println("addressid:"+addressid);*/
		
		String addressStr=request.getParameter("address");
		System.out.println("addressStr:"+addressStr);
		Address address=JSONObject.parseObject(addressStr, Address.class);//收货地址对象
		System.out.println(address.getConsignee()+address.getAddressid());
		
		String goodsidListStr=request.getParameter("goodsidListStr");//购买商品id-num列表字符串
		System.out.println("goodsidListStr:"+goodsidListStr);
		
		double payPrice=Double.parseDouble(request.getParameter("payPrice"));//实际支付价格
		System.out.println("payPrice:"+payPrice);
		double totalPrice=Double.parseDouble(request.getParameter("totalPrice"));//总价
		System.out.println("totalPrice:"+totalPrice);
		double postFee=Double.parseDouble(request.getParameter("postFee"));//邮费
		System.out.println("postFee:"+postFee);
		
		//获取用户对象
		User user=(User) session.getAttribute("user");
		int userid=user.getUserid();
		System.out.println("userid:"+userid);
		
		//提交订单前需要对商品库存表中的商品库存数量进行确认，
		//如果购买数量大于库存则提交订单失败并返回错误信息
		String[] arr=goodsidListStr.split(",");
		//将购买商品的id-num对应关系转化为二维数组
		int[][] arr2=new int[arr.length][2];
		for(int i = 0;i<arr.length;i++) {
			arr2[i][0]=Integer.parseInt(arr[i].split(":")[0]);
			arr2[i][1]=Integer.parseInt(arr[i].split(":")[1]);
		}
		for(int i=0;i<arr2.length;i++) {
			System.out.println(Arrays.toString(arr2[i]));
		}
		boolean flag=false;
		StringBuffer message=new StringBuffer();//如果购买数量超过了库存，返回错误信息2，并将超出数量的商品id返回
		message.append("{\"code\":\"2\",\"codeMsg\":[");
		//{错误代码：2，错误信息：codeMsg：[goodsid1,goodsid2,...]}
		for(int i=0;i<arr2.length;i++) {
			int goodsid=arr2[i][0];
			int goodsNum=arr2[i][1];
			int count=pdao.queryByGoodsid(goodsid).get(0).getCount();
			if(goodsNum>count) {
				flag=true;
				message.append("\""+goodsid+"\",");
			}
		}
		if(flag==true) {
			message.deleteCharAt(message.length()-1);
			message.append("]}");
			out.print(message);
			return;
		}
		else {
//			1.在商品详情表goods_info中减去对应商品的库存数量
			for(int i=0;i<arr2.length;i++) {
				int goodsid=arr2[i][0];
				int goodsNum=arr2[i][1];
				pdao.updateCountByGoosidAndNum(goodsid, goodsNum);
			}
			
//			2.生成订单信息，在order_info表中生成一条新纪录，包括userid/addressid/，
//			支付状态pay_status默认为0待支付，配送状态post_status默认为0待发货，
//			订单状态order_status默认为0待支付，以及goods_num/totle_price/pay_price/
//			points_used/post_fee/create_time/update_time
			oidao.addOrderRecord(userid, address.getAddressid(), 0, 0, 0, arr2.length, totalPrice, payPrice, 0, postFee);
			
//			3.生成订单详情信息，在order_detail中依次添加对应订单表中的商品信息记录，
//			包括orderid/goodsid/num/price/cost/subtotal/status
			int orderid=oidao.queryNewstByUserid(userid).get(0).getOrderid();
			for(int i=0;i<arr2.length;i++) {
				int goodsid=arr2[i][0];
				int goodsNum=arr2[i][1];
				Goods goods=pdao.queryByGoodsid(goodsid).get(0);
				oddao.addOrderDetailRecord(orderid, goodsid, goodsNum, goods.getPrice(), goods.getCost(), goods.getPrice()*goodsNum, 0);
			}
			
//			4.生成订单日志信息，在order_log表中新增一条记录，包括orderid/content:生成订单/operatorid：userid/
//			operator_type：0/time
			String content="订单已提交";
			oldao.addOrderLogRecord(orderid, content, userid, 0);
			
//			5.在用户表user_info中修改对应用户的points/exp/level
			int level=user.getLevel();
			int points=(int) Math.ceil(payPrice/10);
			int exp=points;
			level=(int) Math.floor((exp+user.getExp())/10000);
			udao.updatePointsAndExpByUserid(points, exp, level, userid);
			
//			6.在用户的购物车对象以及表中根据购买的数量减去对应商品的数量,如果数量减完为0则去除购物车的商品记录
			CartShop cartShop=(CartShop) session.getAttribute("cartShop");
			Map<Integer,Integer> cartMap=cartShop.getCarts();
			List<Cart> cartList=cdao.queryByUserid(userid);
			for(int i=0;i<arr2.length;i++) {
				int goodsid=arr2[i][0];
				int goodsNum=arr2[i][1];
				/*for(Iterator<Cart> it=cartList.iterator();it.hasNext();) {
					Cart cart=it.next();
					if(cart.getGoodsid()==goodsid) {
						int num=cart.getGoodsNum()-goodsNum>0?cart.getGoodsNum()-goodsNum:0;
						if(num>0) {
							cdao.updateNum(userid, goodsid, num);
						}
						else {
							cdao.deleteGoods(userid, goodsid);
						}
					}
				}*/
				Map<Integer,Integer> deleteMap=new HashMap<Integer,Integer>();
				for(Map.Entry<Integer, Integer> en:cartMap.entrySet()) {
					if(en.getKey()==goodsid) {
						deleteMap.put(goodsid, en.getValue());
					}
				}
				if(!deleteMap.isEmpty()||deleteMap.size()!=0) {
					for(Map.Entry<Integer, Integer> en:deleteMap.entrySet()) {
						int deleteGoodsid=en.getKey();
						int num=en.getValue();
						num=num-goodsNum>0?num-goodsNum:0;
						cartShop.updateNum(userid, deleteGoodsid, num);
					}
				}
			}
			session.setAttribute("cartShop", cartShop);
			
			message=new StringBuffer();
			/*{
				"data": {
					"code": "1",
					"codeMsg": {
						"orderid": "1",
						"payPrice": "16597.0",
						"addressid ": "1 "
					}
				}
			}*/
			message.append("{\"code\":\"1\",\"codeMsg\":{\"orderid\":\""
					+orderid+"\",\"payPrice\":\""+payPrice+"\",\"addressid\":\""+
					address.getAddressid()+"\"}}");
			//{正确代码：1}
			//订单生成完毕，返回正确代码
			out.print(message);
		}
	}
}
